const { items } = require('../public/javascripts/utils');
const item = items(__filename);

const User = require('../models/users');
class ItemService {
  async create(ctx) {
    try {
      return await item.create(ctx);
    } catch (error) {
      throw error;
    }
  }

  async findAll(ctx) {
    try {
      const { senderId, receiverId } = ctx
      const pageIndex = parseInt(ctx.pageIndex) || 1
      const pageSize = parseInt(ctx.pageSize) || 10
      const skip = (pageIndex - 1) * pageSize
      const total = await item.countDocuments({
        $or: [
          { senderId: senderId, receiverId: receiverId },
          { senderId: receiverId, receiverId: senderId }
        ]
      });
      const res = await item.find({
        $or: [
          { senderId: senderId, receiverId: receiverId },
          { senderId: receiverId, receiverId: senderId }
        ]
      })
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(pageSize)
      .populate('senderId', 'username').populate('receiverId', 'username');
      return { res, total };
    } catch (error) {
      throw error;
    }
  }

  async findByUsers(currentUserId) {
    console.log(currentUserId)
    try {
      // 查询所有与当前用户有过聊天记录的消息
      const messages = await item.find({
        $or: [
          { senderId: currentUserId },
          { receiverId: currentUserId }
        ]
      });
      // 提取所有不同的用户 ID
      const userIds = new Set();
      messages.forEach(message => {
        if (message.senderId.toString() !== currentUserId) {
          userIds.add(message.senderId.toString());
        }
        if (message.receiverId.toString() !== currentUserId) {
          userIds.add(message.receiverId.toString());
        }
      });

      const uniqueUserIds = Array.from(userIds);

      // 查询这些用户的详细信息
      const users = await User.find({ _id: { $in: uniqueUserIds } });
      return users;
    } catch (error) {
      throw error;
    }
  }
}


module.exports = new ItemService();